﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using MTRC.ODMS.Model.SOM.PassengerFlow;
using System.Globalization;
using APJ.Util;

namespace MTRC.ODMS.Web.SOM.PassengerFlow
{
    public partial class PassengerFlowEntry : BasePage_SOM
    {
        #region MenuID

        protected override string MenuID
        {
            get
            {
                return "M141002";
            }
        }

        #endregion

        #region Property
        /// <summary>
        /// 1.Add 2.Edit
        /// </summary>
        public int Action { get; set; }

        private int PsgFlowID
        {
            get
            {
                return string.IsNullOrEmpty(Request.Form["PsgFlowID"]) ? 0 : int.Parse(Request.Form["PsgFlowID"]);
            }
        }

        private int PsgLocationID
        {
            get
            {
                return string.IsNullOrEmpty(Request.Form["PsgLocationID"]) ? 0 : int.Parse(Request.Form["PsgLocationID"]);
            }
        }

        private List<int> Cases = new List<int>();
        #endregion

        #region PageEvent



        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            this.ChangeLanguage += new ChangeLanguageEventHandler(SetLanguage_Click);
        }

        private void RejectRequess()
        {
            string v = DAL.CommonData.GetStrVal("SOM_PassengerFlow_NotReqToFill");
            DataTable dt = DAL.SOM.PassengerFlow.PassengerSelectionCriteria.GetCurrentLocation(this.ODMUser.LocationID, this.LangCode);
            string locationCode = dt.Rows.Count > 0 ? dt.Rows[0]["Code"].ToString() : "";
            if (v.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries).Contains(locationCode))
            {
                string script = "<script>alert('" + GetMessage("SOM_PsgNoPassengerFlow") + "');location.href='PassengerFlowEnquiry.aspx';</script>";
                Response.Write(script);
                Response.End();
                return;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            RejectRequess();

            SaveEvent();

            if (!IsPostBack)
            {
                SetLanguage();
                FunctionItemSetting();
            }
        }

        void SetLanguage_Click(object sender, EventArgs e)
        {
            SetLanguage();
            if (IsPostBack)
            {
                FunctionItemSetting();
            }
        }

        private bool NoPremissionToAccess(ref string messageKey)
        {
            bool result = false;
            DataTable dt = null;
            //add by gordon 20150902 U70
            string psgLocationId = Request.QueryString["psgLocationId"];
            if (DAL.Security.User.CanFunctionItemAccess("M141002_F2", this.ODMUser.UserProfileID, this.MenuID))//access all station.
            {
                //update by gordon 20151020 U247
                //dt = DAL.SOM.CodeSetup.CDAssetType.AccessStationWithUserID(this.ODMUser.ID, true, Convert.ToInt16(LangCode), this.ODMUser.StationID);
                dt = DAL.SOM.CodeSetup.CDAssetType.AccessStationWithUserID(this.ODMUser.ID, true, Convert.ToInt16(LangCode), this.ODMUser.LocationID);
            }
            else if (DAL.Security.User.CanFunctionItemAccess("M141002_F3", this.ODMUser.UserProfileID, this.MenuID))//Can Access other stations.
            {
                //update by gordon 20151020 U247
                //dt = DAL.SOM.CodeSetup.CDAssetType.AccessStationWithUserID(this.ODMUser.ID, false, Convert.ToInt16(LangCode), this.ODMUser.StationID);
                dt = DAL.SOM.CodeSetup.CDAssetType.AccessStationWithUserID(this.ODMUser.ID, false, Convert.ToInt16(LangCode), this.ODMUser.LocationID);
            }

            if (dt != null)
            {
                //int count = dt.Select("LocationID=" + this.ODMUser.LocationID.ToString()).Length;
                int count = dt.Select("LocationID=" + (string.IsNullOrEmpty(psgLocationId) ? "-1" : psgLocationId)).Length;
                result = count < 1;
            }
            else
            {
                //delete by gordon 20150902 U70
                //string psgLocationId = Request.QueryString["psgLocationId"];
                result = psgLocationId != this.ODMUser.LocationID.ToString();
            }

            if (!result)
            {
                int lid = -1;
                int.TryParse(psgLocationId, out lid);
                //update by gordon 20151024 U248
                //result = !BLL.SOM.PassengerFlow.PassengerFlowBLL.IsStation(lid);
                result = !IsValidStation(lid);
            }

            //if (!result)
            //{
            //    messageKey = "SOM_EventNotValidStation";
            //    //add by gordon 20150902
            //    int lid = -1;
            //    int.TryParse(psgLocationId, out lid);
            //    result = !IsValidStation(lid,true);
            //}

            return result;
        }

        private void InitPage()
        {
            string psgFlowId = Request.QueryString["psgFlowId"];
            string psgLocationId = Request.QueryString["psgLocationId"];
            this.Action = (string.IsNullOrEmpty(psgFlowId) || string.IsNullOrEmpty(psgLocationId)) ? 1 : 2;
            hdnPsgFlowID.Value = psgFlowId;
            hdnPsgLocationID.Value = psgLocationId;

            int locationId = this.ODMUser.LocationID;

            if (Action == 1)
            {
                //add by gordon 20150902 U70
                //update by gordon 20151024 U248
                //if (!IsValidStation(locationId, true))
                if (!IsValidStation(locationId))
                {
                    Response.Write("<script>alert('" + this.GetMessage("SOM_NotValidStation") + "');window.location.href='PassengerFlowEnquiry.aspx?IsReject=1'</script>");
                    Response.End();
                    return;
                }

                bool flag = GenerateControl(locationId);
                if (!flag)
                {
                    PageReadOnly(true);
                }

                //add by gordon 20150814
                bool exists = BLL.SOM.PassengerFlow.PassengerFlowBLL.OperatingDayExists(this.ConvertToDateTime(dtOperatingDay.Text), this.ODMUser.LocationID);
                if (exists)
                {
                    dtOperatingDay.Text = string.Empty;
                }
            }
            else if (Action == 2)
            {
                string messageKey = "SOM_NotPermissionStation";
                if (NoPremissionToAccess(ref messageKey))
                {
                    //update by gordon 20150902 U70
                    //PageReadOnly(true);
                    Response.Write("<script>alert('" + this.GetMessage(messageKey) + "');window.location.href='PassengerFlowEnquiry.aspx'</script>");
                    Response.End();
                    return;
                    //Response.Redirect("PassengerFlowEnquiry.aspx");
                }
                else
                {
                    locationId = int.Parse(psgLocationId);
                    DataTable dt = GetPsgData(int.Parse(string.IsNullOrEmpty(psgFlowId) ? "0" : psgFlowId), locationId);
                    if (dt.Rows.Count > 0)
                    {
                        bool flag = GenerateControl(locationId);
                        if (flag)
                        {
                            BindPsgData(dt);
                            dtOperatingDay.Enabled = false;
                        }
                        else
                        {
                            PageReadOnly(true);
                        }
                    }
                    else
                    {
                        PageReadOnly(true);
                    }

                    if (this.ODMUser.LocationID != int.Parse(Request.QueryString["psgLocationID"]))
                    {
                        PageReadOnly(true);
                    }
                }
            }
        }

        private void SetLanguage()
        {
            lblOperatingDay.Text = GetLabel("SOM_PsgOperatingDay") + "<em>*</em>";
            btnSave.Text = GetLabel("SOM_PsgSave");
            btnCancel.Text = GetLabel("SOM_PsgCancel");

            dtOperatingDay.SetDateTime(DateTime.Now.AddDays(-1));

            InitPage();
        }

        private void FunctionItemSetting()
        {
            //Page Read Only
            bool IsReadOnly = DAL.Security.User.CanFunctionItemAccess("M141002_F1", this.ODMUser.UserProfileID, this.MenuID);
            if (IsReadOnly)
            //update by gordon 20150911 U204
            //PageReadOnly(IsReadOnly);
            {
                if (this.Action == 1)
                {
                    Response.Write("<script>alert('" + this.GetMessage("SOM_NotAllowCreateNewEntry") + "');window.location.href='PassengerFlowEnquiry.aspx'</script>");
                    Response.End();
                    return;
                }
                else if (this.Action == 2)
                {
                    PageReadOnly(IsReadOnly);
                }

            }

        }

        private void PageReadOnly(bool readOnly)
        {
            dtOperatingDay.Enabled = !readOnly;
            btnSave.Enabled = !readOnly;
            btnCancel.Enabled = !readOnly;

            #region Disabled 4 Case Control
            foreach (Control c in plPsgCaseOne.Controls)
            {
                if (c is TextBox || c is CheckBox)
                {
                    c.GetType().GetProperty("Enabled").SetValue(c, !readOnly, null);
                }
            }

            foreach (Control c in plPsgCaseTwo.Controls)
            {
                if (c is TextBox || c is CheckBox)
                {
                    c.GetType().GetProperty("Enabled").SetValue(c, !readOnly, null);
                }
            }

            foreach (Control c in plPsgCaseThree.Controls)
            {
                if (c is TextBox || c is CheckBox)
                {
                    c.GetType().GetProperty("Enabled").SetValue(c, !readOnly, null);
                }
            }

            foreach (Control c in plPsgCaseFour.Controls)
            {
                if (c is TextBox || c is CheckBox)
                {
                    c.GetType().GetProperty("Enabled").SetValue(c, !readOnly, null);
                }
            }
            #endregion
        }

        private void AddControl(DataRow datasource, Panel container, int width, int caseId, int index = -1)
        {
            string keyBoardOnKeyPress = "onkeypress";
            string keyboardOnKeyPressEvent = "checkDate2(this,10,0)";
            string keyBoradOnKeyUp = "onkeyup";
            string keyBoradOnKeyUpEvent = "replaceAndSetPos(this, /[^\\d]/g, '')";
            // add by dylan 20150930 for u167
            string keyBoardOnpaste = "onpaste";
            //string keyBoardOnpasteEvent = "return !clipboardData.getData('text').match(/\\D/)";
            // edit by dylan 20151028 for u91
            string keyBoardOnpasteEvent = "return checkPasteText(this.value);";
            bool FlagIncomming = Convert.ToBoolean(datasource["FlagIncoming"]);
            if (FlagIncomming)
            {
                Label lblIn = new Label();
                lblIn.ID = "lblIn" + "_" + caseId.ToString() + (index == -1 ? "" : index.ToString());
                lblIn.Text = GetLabel("SOM_PsgIncoming", true) + "<em>*</em>";
                lblIn.Width = width;
                TextBox txtIn = new TextBox();
                txtIn.ID = "txtIn" + "_" + caseId.ToString() + (index == -1 ? "" : index.ToString());
                txtIn.Attributes.Add(keyBoardOnKeyPress, keyboardOnKeyPressEvent);
                txtIn.Attributes.Add(keyBoradOnKeyUp, keyBoradOnKeyUpEvent);
                // add by dylan 20150930 for u167
                txtIn.Attributes.Add(keyBoardOnpaste, keyBoardOnpasteEvent);
                txtIn.MaxLength = 10;
                CheckBox chkIn = new CheckBox();
                chkIn.ID = "chkIn" + "_" + caseId.ToString() + (index == -1 ? "" : index.ToString());
                chkIn.Text = GetLabel("SOM_PsgEstimate");
                container.Controls.Add(lblIn);
                container.Controls.Add(txtIn);
                container.Controls.Add(chkIn);
                container.Controls.Add(new Literal() { Text = "<br/>" });
            }

            bool FlagOutgoing = Convert.ToBoolean(datasource["FlagOutgoing"]);
            if (FlagOutgoing)
            {
                Label lblOut = new Label();
                lblOut.ID = "lblOut" + "_" + caseId.ToString() + (index == -1 ? "" : index.ToString());
                lblOut.Text = GetLabel("SOM_PsgOutgoing", true) + "<em>*</em>";
                lblOut.Width = width;
                TextBox txtOut = new TextBox();
                txtOut.ID = "txtOut" + "_" + caseId.ToString() + (index == -1 ? "" : index.ToString());
                txtOut.MaxLength = 10;
                txtOut.Attributes.Add(keyBoardOnKeyPress, keyboardOnKeyPressEvent);
                txtOut.Attributes.Add(keyBoradOnKeyUp, keyBoradOnKeyUpEvent);
                // add by dylan 20150930 for u167
                txtOut.Attributes.Add(keyBoardOnpaste, keyBoardOnpasteEvent);
                CheckBox chkOut = new CheckBox();
                chkOut.ID = "chkOut" + "_" + caseId.ToString() + (index == -1 ? "" : index.ToString());
                chkOut.Text = GetLabel("SOM_PsgEstimate");
                container.Controls.Add(lblOut);
                container.Controls.Add(txtOut);
                container.Controls.Add(chkOut);
                container.Controls.Add(new Literal() { Text = "<br/>" });
            }

            bool FlagTransit = Convert.ToBoolean(datasource["FlagTransit"]);
            if (FlagTransit)
            {
                Label lblTST = new Label();
                lblTST.ID = "lblTST" + "_" + caseId.ToString() + (index == -1 ? "" : index.ToString());
                lblTST.Text = GetLabel("SOM_PsgTSTTransit", true) + "<em>*</em>";
                lblTST.Width = width;
                TextBox txtTST = new TextBox();
                txtTST.ID = "txtTST" + "_" + caseId.ToString() + (index == -1 ? "" : index.ToString());
                txtTST.MaxLength = 10;
                txtTST.Attributes.Add(keyBoardOnKeyPress, keyboardOnKeyPressEvent);
                txtTST.Attributes.Add(keyBoradOnKeyUp, keyBoradOnKeyUpEvent);
                // add by dylan 20150930 for u167
                txtTST.Attributes.Add(keyBoardOnpaste, keyBoardOnpasteEvent);
                CheckBox chkTST = new CheckBox();
                chkTST.ID = "chkTST" + "_" + caseId.ToString() + (index == -1 ? "" : index.ToString());
                chkTST.Text = GetLabel("SOM_PsgEstimate");
                container.Controls.Add(lblTST);
                container.Controls.Add(txtTST);
                container.Controls.Add(chkTST);
                container.Controls.Add(new Literal() { Text = "<br/>" });

                Label lblETS = new Label();
                lblETS.ID = "lblETS" + "_" + caseId.ToString() + (index == -1 ? "" : index.ToString());
                lblETS.Text = GetLabel("SOM_PsgETSTransit", true) + "<em>*</em>";
                lblETS.Width = width;
                TextBox txtETS = new TextBox();
                txtETS.ID = "txtETS" + "_" + caseId.ToString() + (index == -1 ? "" : index.ToString());
                txtETS.MaxLength = 10;
                txtETS.Attributes.Add(keyBoardOnKeyPress, keyboardOnKeyPressEvent);
                txtETS.Attributes.Add(keyBoradOnKeyUp, keyBoradOnKeyUpEvent);
                // add by dylan 20150930 for u167
                txtETS.Attributes.Add(keyBoardOnpaste, keyBoardOnpasteEvent);
                CheckBox chkETS = new CheckBox();
                chkETS.ID = "chkETS" + "_" + caseId.ToString() + (index == -1 ? "" : index.ToString());
                chkETS.Text = GetLabel("SOM_PsgEstimate");
                container.Controls.Add(lblETS);
                container.Controls.Add(txtETS);
                container.Controls.Add(chkETS);
                container.Controls.Add(new Literal() { Text = "<br/>" });
            }

        }

        private bool GenerateControl(int locationId)
        {
            DataSet ds = BLL.SOM.PassengerFlow.PassengerFlowBLL.GetPassengerFlowControl(locationId, this.LangCode);

            if (ds.Tables.Count == 4)
            {
                if (ds.Tables[0].Rows.Count < 1 && ds.Tables[1].Rows.Count < 1 && ds.Tables[2].Rows.Count < 1 && ds.Tables[3].Rows.Count < 1)
                {
                    return false;
                }
            }

            if (ds.Tables.Count == 3)
            {
                if (ds.Tables[0].Rows.Count < 1 && ds.Tables[1].Rows.Count < 1 && ds.Tables[2].Rows.Count < 1)
                {
                    return false;
                }
            }

            //Label Width
            int width = 90;

            //4 RowSet
            if (ds.Tables.Count == 4)
            {
                #region Case 1
                //case 1
                DataTable caseDtOne = ds.Tables[0];
                if (caseDtOne.Rows.Count > 0 && caseDtOne.Select("Case=1").Length > 0)
                {
                    Label lblIO = new Label();
                    lblIO.Text = caseDtOne.Rows[0]["Description"].ToString() + " " + caseDtOne.Rows[0]["CurrentLocationCode"].ToString();
                    lblIO.ID = "lblIO_1";
                    lblIO.Font.Bold = true;
                    lblIO.Font.Underline = true;
                    lblIO.Attributes.Add("PsgFlowTypeID", caseDtOne.Rows[0]["PsgFlowTypeID"].ToString());
                    plPsgCaseOne.Controls.Add(lblIO);
                    plPsgCaseOne.Controls.Add(new Literal() { Text = "<br/>" });

                    AddControl(caseDtOne.Rows[0], plPsgCaseOne, width, 1);

                    Cases.Add(1);
                }
                #endregion
                #region Case 2
                //case 2
                DataTable caseDtTwo = ds.Tables[1];
                if (caseDtTwo.Rows.Count > 0 && caseDtTwo.Select("Case=2").Length > 0)
                {
                    HiddenField hdnRowCount = new HiddenField();
                    hdnRowCount.ID = "hdnRowCount";
                    hdnRowCount.Value = caseDtTwo.Rows.Count.ToString();
                    plPsgCaseTwo.Controls.Add(hdnRowCount);

                    int index = 0;
                    foreach (DataRow dr in caseDtTwo.Rows)
                    {
                        Label lblIO = new Label();
                        lblIO.ID = "lblIO_2" + index;
                        lblIO.Text = dr["Description"].ToString();
                        lblIO.Font.Bold = true;
                        lblIO.Font.Underline = true;
                        lblIO.Attributes.Add("PsgFlowTypeID", dr["PsgFlowTypeID"].ToString());
                        plPsgCaseTwo.Controls.Add(lblIO);
                        plPsgCaseTwo.Controls.Add(new Literal() { Text = "<br/>" });

                        AddControl(dr, plPsgCaseTwo, width, 2, index++);
                    }

                    Cases.Add(2);
                }
                #endregion
                #region Add Separator Line
                //add separator line
                separatorLine.Visible = (caseDtOne.Rows.Count > 0 || caseDtTwo.Rows.Count > 0) && (ds.Tables[2].Rows.Count > 0 || ds.Tables[3].Rows.Count > 0);
                #endregion
                #region Case 3
                //case 3
                DataTable caseDtThree = ds.Tables[2];
                if (caseDtThree.Rows.Count > 0 && caseDtThree.Select("Case=3").Length > 0)
                {
                    Label lblIO = new Label();
                    lblIO.ID = "lblIO_3";
                    lblIO.Text = (caseDtThree.Rows[0]["Description"].ToString() + " " + caseDtThree.Rows[0]["CurrentLocationCode"].ToString()).TrimStart();
                    lblIO.Font.Underline = true;
                    lblIO.Font.Bold = true;
                    lblIO.Attributes.Add("PsgFlowTypeID", caseDtThree.Rows[0]["PsgFlowTypeID"].ToString());
                    plPsgCaseThree.Controls.Add(lblIO);
                    plPsgCaseThree.Controls.Add(new Literal() { Text = "<br/>" });

                    AddControl(caseDtThree.Rows[0], plPsgCaseThree, width, 3);

                    Cases.Add(3);
                }
                #endregion
                #region Case 4
                //case 4
                DataTable caseDtFour = ds.Tables[3];
                if (caseDtFour.Rows.Count > 0 && caseDtFour.Select("Case=4").Length > 0)
                {
                    Label lblIO = new Label();
                    lblIO.ID = "lblIO_4";
                    lblIO.Text = (caseDtFour.Rows[0]["Description"].ToString() + " " + caseDtFour.Rows[0]["CurrentLocationCode"].ToString()).TrimStart();
                    lblIO.Font.Underline = true;
                    lblIO.Font.Bold = true;
                    lblIO.Attributes.Add("PsgFlowTypeID", caseDtFour.Rows[0]["PsgFlowTypeID"].ToString());
                    plPsgCaseFour.Controls.Add(lblIO);
                    plPsgCaseFour.Controls.Add(new Literal() { Text = "<br/>" });

                    AddControl(caseDtFour.Rows[0], plPsgCaseFour, width, 4);

                    Cases.Add(4);
                }
                #endregion

            }
            //3 RowSet
            else if (ds.Tables.Count == 3)
            {
                #region Case 1
                //case 1
                DataTable caseDtOne = ds.Tables[0];
                if (caseDtOne.Rows.Count > 0 && caseDtOne.Select("Case=1").Length > 0)
                {
                    Label lblIO = new Label();
                    lblIO.Text = caseDtOne.Rows[0]["Description"].ToString() + " " + caseDtOne.Rows[0]["CurrentLocationCode"].ToString();
                    lblIO.ID = "lblIO_1";
                    lblIO.Font.Bold = true;
                    lblIO.Font.Underline = true;
                    lblIO.Attributes.Add("PsgFlowTypeID", caseDtOne.Rows[0]["PsgFlowTypeID"].ToString());
                    plPsgCaseOne.Controls.Add(lblIO);
                    plPsgCaseOne.Controls.Add(new Literal() { Text = "<br/>" });

                    AddControl(caseDtOne.Rows[0], plPsgCaseOne, 1, width);

                    Cases.Add(1);
                }
                #endregion
                #region Case 2
                //case 2
                DataTable caseDtTwo = ds.Tables[1];
                if (caseDtTwo.Rows.Count > 0 && caseDtTwo.Select("Case=2").Length > 0)
                {
                    HiddenField hdnRowCount = new HiddenField();
                    hdnRowCount.ID = "hdnRowCount";
                    hdnRowCount.Value = caseDtTwo.Rows.Count.ToString();
                    plPsgCaseTwo.Controls.Add(hdnRowCount);

                    int index = 0;
                    foreach (DataRow dr in caseDtTwo.Rows)
                    {
                        Label lblIO = new Label();
                        lblIO.ID = "lblIO_2" + index;
                        lblIO.Text = dr["Description"].ToString();
                        lblIO.Font.Bold = true;
                        lblIO.Font.Underline = true;
                        lblIO.Attributes.Add("PsgFlowTypeID", dr["PsgFlowTypeID"].ToString());
                        plPsgCaseTwo.Controls.Add(lblIO);
                        plPsgCaseTwo.Controls.Add(new Literal() { Text = "<br/>" });

                        AddControl(dr, plPsgCaseTwo, width, 2, index++);
                    }

                    Cases.Add(2);
                }
                #endregion
                #region Add Separator Line
                //add separator line
                separatorLine.Visible = (caseDtOne.Rows.Count > 0 || caseDtTwo.Rows.Count > 0) && (ds.Tables[2].Rows.Count > 0 || ds.Tables[3].Rows.Count > 0);
                #endregion
                #region Case 3 or Case 4
                if (ds.Tables[2].Select("Case=3").Length > 0)
                {
                    #region Case 3
                    //case 3
                    DataTable caseDtThree = ds.Tables[2];
                    if (caseDtThree.Rows.Count > 0 && caseDtThree.Select("Case=3").Length > 0)
                    {
                        Label lblIO = new Label();
                        lblIO.ID = "lblIO_3";
                        lblIO.Text = (caseDtThree.Rows[0]["Description"].ToString() + " " + caseDtThree.Rows[0]["CurrentLocationCode"].ToString()).TrimStart();
                        lblIO.Font.Underline = true;
                        lblIO.Font.Bold = true;
                        lblIO.Attributes.Add("PsgFlowTypeID", caseDtThree.Rows[0]["PsgFlowTypeID"].ToString());
                        plPsgCaseThree.Controls.Add(lblIO);
                        plPsgCaseThree.Controls.Add(new Literal() { Text = "<br/>" });

                        AddControl(caseDtThree.Rows[0], plPsgCaseThree, width, 3);

                        Cases.Add(3);
                    }
                    #endregion
                }
                else if (ds.Tables[2].Select("Case=4").Length > 0)
                {
                    #region Case 4
                    //case 4
                    DataTable caseDtFour = ds.Tables[3];
                    if (caseDtFour.Rows.Count > 0 && caseDtFour.Select("Case=4").Length > 0)
                    {
                        Label lblIO = new Label();
                        lblIO.ID = "lblIO_4";
                        lblIO.Text = (caseDtFour.Rows[0]["Description"].ToString() + " " + caseDtFour.Rows[0]["CurrentLocationCode"].ToString()).TrimStart();
                        lblIO.Font.Underline = true;
                        lblIO.Font.Bold = true;
                        lblIO.Attributes.Add("PsgFlowTypeID", caseDtFour.Rows[0]["PsgFlowTypeID"].ToString());
                        plPsgCaseFour.Controls.Add(lblIO);
                        plPsgCaseFour.Controls.Add(new Literal() { Text = "<br/>" });

                        AddControl(caseDtFour.Rows[0], plPsgCaseFour, width, 4);

                        Cases.Add(4);
                    }
                    #endregion
                }
                #endregion
            }

            return true;
        }

        private DataTable GetPsgData(int PsgFlowID, int LocationID)
        {
            return BLL.SOM.PassengerFlow.PassengerFlowBLL.GetPsg(PsgFlowID, LocationID);
        }

        private void BindValue(DataTable dt, Panel container, int caseId, int index = -1)
        {
            int flowTypeID = -1;
            Label lblIO = container.FindControl("lblIO" + "_" + caseId.ToString() + (index == -1 ? "" : index.ToString())) as Label;
            if (lblIO != null)
            {
                flowTypeID = int.Parse(lblIO.Attributes["PsgFlowTypeID"]);
            }

            DataRow[] drs = dt.Select("PsgFlowTypeID=" + flowTypeID);
            if (drs.Length > 0)
            {
                TextBox txtIn = container.FindControl("txtIn" + "_" + caseId.ToString() + (index == -1 ? "" : index.ToString())) as TextBox;
                if (txtIn != null)
                {
                    txtIn.Text = drs[0]["Incoming"] == null ? "" : drs[0]["Incoming"].ToString();
                }

                CheckBox chkIn = container.FindControl("chkIn" + "_" + caseId.ToString() + (index == -1 ? "" : index.ToString())) as CheckBox;
                if (chkIn != null)
                {
                    chkIn.Checked = drs[0]["FlagEstIncoming"] == null ? false : Convert.ToBoolean(drs[0]["FlagEstIncoming"]);
                }

                TextBox txtOut = container.FindControl("txtOut" + "_" + caseId.ToString() + (index == -1 ? "" : index.ToString())) as TextBox;
                if (txtOut != null)
                {
                    txtOut.Text = drs[0]["Outgoing"] == null ? "" : drs[0]["Outgoing"].ToString();
                }

                CheckBox chkOut = container.FindControl("chkOut" + "_" + caseId.ToString() + (index == -1 ? "" : index.ToString())) as CheckBox;
                if (chkOut != null)
                {
                    chkOut.Checked = drs[0]["FlagEstOutgoing"] == null ? false : Convert.ToBoolean(drs[0]["FlagEstOutgoing"]);
                }

                TextBox txtTST = container.FindControl("txtTsT" + "_" + caseId.ToString() + (index == -1 ? "" : index.ToString())) as TextBox;
                if (txtTST != null)
                {
                    txtTST.Text = drs[0]["TransitTST"] == null ? "" : drs[0]["TransitTST"].ToString();
                }

                CheckBox chkTST = container.FindControl("chkTST" + "_" + caseId.ToString() + (index == -1 ? "" : index.ToString())) as CheckBox;
                if (chkTST != null)
                {
                    chkTST.Checked = drs[0]["FlagEstTransitTST"] == null ? false : Convert.ToBoolean(drs[0]["FlagEstTransitTST"]);
                }

                TextBox txtETS = container.FindControl("txtETS" + "_" + caseId.ToString() + (index == -1 ? "" : index.ToString())) as TextBox;
                if (txtETS != null)
                {
                    txtETS.Text = drs[0]["TransitETS"] == null ? "" : drs[0]["TransitETS"].ToString();
                }

                CheckBox chkETS = container.FindControl("chkETS" + "_" + caseId.ToString() + (index == -1 ? "" : index.ToString())) as CheckBox;
                if (chkETS != null)
                {
                    chkETS.Checked = drs[0]["FlagEstTransitETS"] == null ? false : Convert.ToBoolean(drs[0]["FlagEstTransitETS"]);
                }
            }
        }

        private void BindPsgData(DataTable dt)
        {
            if (dt.Rows.Count > 0)
            {
                //Case One
                BindValue(dt, plPsgCaseOne, 1);

                //Case Two
                HiddenField hdnRowCount = plPsgCaseTwo.FindControl("hdnRowCount") as HiddenField;
                if (hdnRowCount != null)
                {
                    int counts = int.Parse(hdnRowCount.Value);
                    for (int i = 0; i < counts; i++)
                    {
                        BindValue(dt, plPsgCaseTwo, 2, i);
                    }
                }

                //Case Three
                BindValue(dt, plPsgCaseThree, 3);

                //Case Four
                BindValue(dt, plPsgCaseFour, 4);

                dtOperatingDay.SetDateTime(this.ConvertToDateTime(dt.Rows[0]["OperatingDay"].ToString()));
            }
        }

        #endregion

        #region ButtonEvent

        private bool SetData(DataRow dr, string[] data)
        {
            if (data[1] == "N")
                return false;

            dr["OperatingDay"] = this.ConvertToDateTime(data[0]);
            dr["LocationID"] = PsgLocationID == 0 ? this.ODMUser.LocationID : PsgLocationID;
            if (data[1] != "N")
                dr["PsgFlowTypeID"] = int.Parse(data[1]);
            if (data[2] != "N")
                dr["Incoming"] = long.Parse(data[2]);
            if (data[3] != "N")
                dr["FlagEstIncoming"] = data[3] == "T" ? true : false;
            if (data[4] != "N")
                dr["Outgoing"] = long.Parse(data[4]);
            if (data[5] != "N")
                dr["FlagEstOutgoing"] = data[5] == "T" ? true : false;
            if (data[6] != "N")
                dr["TransitTST"] = long.Parse(data[6]);
            if (data[7] != "N")
                dr["FlagEstTransitTST"] = data[7] == "T" ? true : false;
            if (data[8] != "N")
                dr["TransitETS"] = long.Parse(data[8]);
            if (data[9] != "N")
                dr["FlagEstTransitETS"] = data[9] == "T" ? true : false;
            dr["CreateUser"] = this.ODMUser.ID;
            dr["CreateTime"] = DateTime.Now;
            dr["LastUpdUser"] = this.ODMUser.ID;
            dr["LastUpdTime"] = DateTime.Now;
            dr["ActingasUser"] = this.ODMUser.ID;
            dr["PsgFlowID"] = PsgFlowID;
            return true;
        }

        private DataTable GetPageData(string[] case1, string[] case2, string[] case3, string[] case4)
        {
            DataTable data = new DataTable();
            data.Columns.Add(new DataColumn("PsgFlowID", typeof(int)));
            data.Columns.Add(new DataColumn("OperatingDay", typeof(DateTime)));
            data.Columns.Add(new DataColumn("LocationID", typeof(int)));
            data.Columns.Add(new DataColumn("PsgFlowTypeID", typeof(int)));
            data.Columns.Add(new DataColumn("Incoming", typeof(long)));
            data.Columns.Add(new DataColumn("Outgoing", typeof(long)));
            data.Columns.Add(new DataColumn("TransitTST", typeof(long)));
            data.Columns.Add(new DataColumn("TransitETS", typeof(long)));
            data.Columns.Add(new DataColumn("FlagEstIncoming", typeof(bool)));
            data.Columns.Add(new DataColumn("FlagEstOutgoing", typeof(bool)));
            data.Columns.Add(new DataColumn("FlagEstTransitTST", typeof(bool)));
            data.Columns.Add(new DataColumn("FlagEstTransitETS", typeof(bool)));
            data.Columns.Add(new DataColumn("CreateUser", typeof(int)));
            data.Columns.Add(new DataColumn("CreateTime", typeof(DateTime)));
            data.Columns.Add(new DataColumn("LastUpdUser", typeof(int)));
            data.Columns.Add(new DataColumn("LastUpdTime", typeof(DateTime)));
            data.Columns.Add(new DataColumn("ActingasUser", typeof(int)));

            DataRow dr;
            bool IsNotNull;
            //Case 1
            dr = data.NewRow();
            IsNotNull = SetData(dr, case1);
            if (IsNotNull)
                data.Rows.Add(dr);

            //Case 2
            foreach (string str in case2)
            {
                dr = data.NewRow();
                IsNotNull = SetData(dr, str.Split(','));
                if (IsNotNull)
                    data.Rows.Add(dr);
            }

            //Case 3
            dr = data.NewRow();
            IsNotNull = SetData(dr, case3);
            if (IsNotNull)
                data.Rows.Add(dr);

            //Case 4
            dr = data.NewRow();
            IsNotNull = SetData(dr, case4);
            if (IsNotNull)
                data.Rows.Add(dr);

            return data;
        }

        private void SaveEvent()
        {
            string action = Request.Form["Action"];
            if (!string.IsNullOrEmpty(action))
            {
                if (action == "1" || action == "2")
                {
                    string msg = "0_0_0_";
                    try
                    {
                        string[] caseOne = Request.Form["CaseOne"].Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
                        string[] caseTwo = Request.Form["CaseTwo"].Split(new string[] { "-" }, StringSplitOptions.RemoveEmptyEntries);
                        string[] caseThree = Request.Form["CaseThree"].Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
                        string[] caseFour = Request.Form["CaseFour"].Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);

                        if (Utility.ConvertToDateTime(caseOne[0], DateTime.MinValue) == DateTime.MinValue)
                        {
                            msg += GetMessage("SOM_PsgOperatingDayFormat");
                        }
                        else if (DateTime.Compare(this.ConvertToDateTime(caseOne[0]), DateTime.Now) > 0)
                        {
                            msg += GetMessage("SOM_PsgOperatingDayNotFuture");
                        }
                        #region Add New
                        else if (action == "1")
                        {

                            try
                            {
                                DateTime operatingDay = this.ConvertToDateTime(caseOne[0]);

                                bool exists = BLL.SOM.PassengerFlow.PassengerFlowBLL.OperatingDayExists(operatingDay, this.ODMUser.LocationID);
                                if (!exists)
                                {
                                    DataTable dt = GetPageData(caseOne, caseTwo, caseThree, caseFour);
                                    int psgFlowID = BLL.SOM.PassengerFlow.PassengerFlowBLL.UpdatePsg(dt, 1);
                                    msg = "1_" + psgFlowID + "_" + this.ODMUser.LocationID + "_" + GetMessage("SaveSuccessfully");
                                }
                                else
                                {
                                    msg += GetMessage("SOM_PsgOperatingDayExists");
                                }
                            }
                            catch (Exception ex)
                            {
                                msg += ex.Message;
                            }
                        }
                        #endregion
                        #region Edit
                        else if (action == "2")
                        {
                            try
                            {
                                DataTable dt = GetPageData(caseOne, caseTwo, caseThree, caseFour);
                                BLL.SOM.PassengerFlow.PassengerFlowBLL.UpdatePsg(dt, 2);
                                msg = "1_" + PsgFlowID + "_" + PsgLocationID + "_" + GetMessage("SaveSuccessfully");
                            }
                            catch (Exception ex)
                            {
                                msg += ex.Message;
                            }
                        }
                        #endregion
                    }
                    catch (Exception ex)
                    {
                        msg += ex.Message;
                    }
                    Response.Write(msg);
                    Response.End();
                    return;
                }
            }

        }

        protected void BtnCancel_Click(object sender, EventArgs e)
        {
            Response.Redirect("PassengerFlowEnquiry.aspx");
        }
        #endregion
    }
}
